package com.reeygu.item.rabbitMQ;

import com.reeygu.item.pojo.SeckillOrder;
import com.reeygu.item.pojo.User;
import com.reeygu.item.service.GoodsService;
import com.reeygu.item.service.OrderService;
import com.reeygu.item.service.SeckillOrderService;
import com.reeygu.item.utils.JsonUtil;
import com.reeygu.item.vo.GoodsVo;
import com.reeygu.item.vo.SeckillMessage;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;

@Slf4j
public class MQReceive {
    @Autowired
    private GoodsService goodsService;
    @Autowired
    private RedisTemplate redisTemplate;
    @Autowired
    private SeckillOrderService seckillOrderService;

    @RabbitListener(queues = "seckillQueue")
    public void seckillReceive(String message) {
        log.info("接收到消息: {}", message);
        SeckillMessage seckillMessage = JsonUtil.jsonStr2Object(message, SeckillMessage.class);
        User user = seckillMessage.getUser();
        Long goodsId = seckillMessage.getGoodsId();
        GoodsVo goodsVoByGoodsId = goodsService.findGoodsVoByGoodsId(goodsId);
        if(goodsVoByGoodsId.getStockCount() < 1) {
            return;
        }
        //在查一遍库存
        SeckillOrder seckillOrder = (SeckillOrder) redisTemplate.opsForValue().get("order:" + user.getId() + ":" + goodsId);
        if (seckillOrder != null) {
            return;
        }
        //下单
        seckillOrderService.generatorKillAndOrder(goodsVoByGoodsId, user);
    }
}
